﻿import { Injectable } from '@angular/core';
import { ToastController, LoadingController, AlertController} from 'ionic-angular';
import { Camera, CameraOptions } from '@ionic-native/camera';
import { DatePicker } from '@ionic-native/date-picker';
import { Contacts, Contact, ContactField, ContactName } from '@ionic-native/contacts';

@Injectable()
export class Utils {
	loader: any;
  constructor(public toastCtrl: ToastController, public loadingCtrl: LoadingController, 
  	public alertCtrl: AlertController, public camera: Camera, public datePicker: DatePicker, 
  	private contacts: Contacts) {

  }

	showAlert(message: string) {
    let toast = this.toastCtrl.create({
      message: message,
      duration: 3000,
      position: 'top',
      dismissOnPageChange: true
    });
    toast.present();
	}

	showLoading() {
		this.loader = this.loadingCtrl.create({
      content: '努力搬砖中...',
      // duration: 3000,
      dismissOnPageChange: false,
      enableBackdropDismiss: false,
      showBackdrop: true
    });
    this.loader.present()
	}

	hideLoading() {
		this.loader.dismiss();
	}

	confirm(message: string) {
		return new Promise((resolve) => {
		  let alert = this.alertCtrl.create({
		    title: '友情提示',
		    message: message || '确定当前操作吗？',
		    buttons: [
		      {
		        text: '取消'
		      },
		      {
		        text: '确定',
		        handler: () => {
		        	alert.dismiss().then(() =>{
		        		resolve();
		        	});
				     return false;
		        }
		      }
		    ]
		  });
		  alert.present();
		});
	}

	getPicture(type: number) {
		let options: CameraOptions = {
		  quality: 100,
		  destinationType: this.camera.DestinationType.DATA_URL,
		  encodingType: this.camera.EncodingType.JPEG,
		  mediaType: this.camera.MediaType.PICTURE,
		  sourceType: type
		}
		return new Promise((resove, reject) => {
			this.camera.getPicture(options).then((imageData) => {
				resove(imageData);
			 // let base64Image = 'data:image/jpeg;base64,' + imageData;
			}, (err) => {
			  reject(err);
			});
		});
	}

	getDate(dateStr?: string) {
		let defaultDate = new Date();
		if(dateStr && dateStr != ''){
			dateStr = dateStr.replace(/-/g,"/");
			defaultDate = new Date(dateStr);
		}
		return new Promise((resove, reject) => {
			this.datePicker.show({
			  date: defaultDate,
			  mode: 'date',
			  androidTheme: this.datePicker.ANDROID_THEMES.THEME_HOLO_DARK
			}).then((res) => {
				let date = Utils.dateFormat(res, 'yyyy-MM-dd')
				resove(date);
			},(err) => {
				reject(err);
			});
		});
	}

	saveContract(name: string, number: string) {
		let contact: Contact = this.contacts.create();
		contact.name = new ContactName(null, name, '');
		contact.phoneNumbers = [new ContactField('mobile', number)];

		return new Promise((resove, reject) => {
			contact.save().then(() => {
			  	console.log('Contact saved!', contact);
			  	resove();
			  },(error: any) => {
			  	console.error('Error saving contact.', error);
			  	reject(error);
			  }
			);
		});
	}

	pickContract() {
		return new Promise((resove, reject) => {
			this.contacts.pickContact().then((contact) => {
			  	resove(contact);
			  },(error: any) => {
			  	reject(error);
			  }
			);
		});
	}

	/**
	 * 日期对象转为日期字符串
	 * @param date 需要格式化的日期对象
	 * @param sFormat 输出格式,默认为yyyy-MM-dd                         年：y，月：M，日：d，时：h，分：m，秒：s
	 * @example  dateFormat(new Date())                                "2017-02-28"
	 * @example  dateFormat(new Date(),'yyyy-MM-dd')                   "2017-02-28"
	 * @example  dateFormat(new Date(),'yyyy-MM-dd hh:mm:ss')         "2017-02-28 09:24:00"
	 * @example  dateFormat(new Date(),'hh:mm')                       "09:24"
	 * @example  dateFormat(new Date(),'yyyy-MM-ddThh:mm:ss+08:00')   "2017-02-28T09:24:00+08:00"
	 * @returns {string}
	 */
	static dateFormat(date: Date, sFormat:string = 'yyyy-MM-dd'): string {
	  let time = {
	    Year: 0,
	    TYear: '0',
	    Month: 0,
	    TMonth: '0',
	    Day: 0,
	    TDay: '0',
	    Hour: 0,
	    THour: '0',
	    hour: 0,
	    Thour: '0',
	    Minute: 0,
	    TMinute: '0',
	    Second: 0,
	    TSecond: '0',
	    Millisecond: 0
	  };
	  time.Year = date.getFullYear();
	  time.TYear = String(time.Year).substr(2);
	  time.Month = date.getMonth() + 1;
	  time.TMonth = time.Month < 10 ? "0" + time.Month : String(time.Month);
	  time.Day = date.getDate();
	  time.TDay = time.Day < 10 ? "0" + time.Day : String(time.Day);
	  time.Hour = date.getHours();
	  time.THour = time.Hour < 10 ? "0" + time.Hour : String(time.Hour);
	  time.hour = time.Hour < 13 ? time.Hour : time.Hour - 12;
	  time.Thour = time.hour < 10 ? "0" + time.hour : String(time.hour);
	  time.Minute = date.getMinutes();
	  time.TMinute = time.Minute < 10 ? "0" + time.Minute : String(time.Minute);
	  time.Second = date.getSeconds();
	  time.TSecond = time.Second < 10 ? "0" + time.Second : String(time.Second);
	  time.Millisecond = date.getMilliseconds();

	  return sFormat.replace(/yyyy/ig, String(time.Year))
	    .replace(/yyy/ig, String(time.Year))
	    .replace(/yy/ig, time.TYear)
	    .replace(/y/ig, time.TYear)
	    .replace(/MM/g, time.TMonth)
	    .replace(/M/g, String(time.Month))
	    .replace(/dd/ig, time.TDay)
	    .replace(/d/ig, String(time.Day))
	    .replace(/HH/g, time.THour)
	    .replace(/H/g, String(time.Hour))
	    .replace(/hh/g, time.Thour)
	    .replace(/h/g, String(time.hour))
	    .replace(/mm/g, time.TMinute)
	    .replace(/m/g, String(time.Minute))
	    .replace(/ss/ig, time.TSecond)
	    .replace(/s/ig, String(time.Second))
	    .replace(/fff/ig, String(time.Millisecond))
	}

}
